/**
 * Create by yxk at 2020/7/8 0008
 */
import { isEmpty } from '@/utils/types'
import { separator } from '@/filters/vueNumeralFilter/filters'
import ListView from './components/ListView'
import { floatAdd } from '@/utils'

export default {
  components: {
    ListView
  },
  data() {
    return {
      loading: false,

      currentPage: 1, // 当前页码
      pageSizes: [15, 30, 60, 100], // 数据条数选项
      pageSize: 15, // 当前每页数据条数
      total: 0, // 数据总条数

      clickedRow: null,
      showListView: false
    }
  },
  computed: {
    /**
     * 可以被点击的字段
     * @return {*[]|*}
     */
    canVisitFields() {
      if (!this.fieldList) return []
      return this.fieldList.filter(o => o.canVisit).map(o => o.fieldName || o.field || o.prop)
    },
    moneyFields() {
      if (!this.fieldList) return []
      return this.fieldList.filter(o => o.isMoney).map(o => o.fieldName || o.field || o.prop)
    }
  },
  created() {
    this.formatterFields()
  },
  methods: {
    getDataList() {},

    getSummaries(param) {
      const { columns, data } = param
      const sums = []
      const that = this
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '合计'
          return
        }
        const values = data.map(item => Number(item[column.property]) || 0)
        if (!values.every(value => isNaN(value))) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr)
            if (!isNaN(value)) {
              return floatAdd(prev, curr)
            } else {
              return prev
            }
          }, 0)
          if (that.moneyFields.includes(column.property)) {
            sums[index] = separator(sums[index])
          }
        } else {
          sums[index] = ''
        }
      })

      return sums
    },

    formatterFields() {
      this.fieldList.forEach(item => {
        if (item.isMoney) {
          item.formatter = function(row, column, cellValue, index) {
            return separator(cellValue || 0)
          }
        } else {
          item.formatter = function(row, column, cellValue, index) {
            return isEmpty(cellValue) ? '--' : cellValue
          }
        }
      })
    },

    /**
     * 通过回调控制class
     */
    cellClassName({ row, column, rowIndex, columnIndex }) {
      return this.canVisitFields.includes(column.property) ? 'can-visit--underline' : ''
    },

    handleRowClick(row, column) {
      if (this.canVisitFields.includes(column.property)) {
        this.clickedRow = row
        if (this.handleTableClick) {
          this.handleTableClick(row, column.property)
        }
      }
    },

    handleSizeChange(size) {
      this.pageSize = size
      this.getDataList()
    },
    handleCurrentChange(page) {
      this.currentPage = page
      this.getDataList()
    }
  }
}
